﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceProcess;
using XBMC.Cache.Manager.Shared;

namespace XBMC.Cache.Manager.Options
{
    public partial class frmMain : Form
    {
        private ServiceControllerStatus m_LastStatus;

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            ctlLED.Border.ChromeWidth = 1;
            ctlLED.Border.RimWidth = 2;
            ctlLED.ThresholdOn.Color = Color.LawnGreen;
            ctlLED.ThresholdOn.Value = 0;
            ctlLED.Threshold1.Color = Color.Orange;
            ctlLED.Threshold1.Value = 2;
            ctlLED.Threshold2.Color = Color.Red;
            ctlLED.Threshold2.Value = 3;

            txtServerName.Text = RegistryHelper.LoadRegistryOption("DBServer");
            txtVideoDatabase.Text = RegistryHelper.LoadRegistryOption("DBVideoDBName");
            txtMusicDatabase.Text = RegistryHelper.LoadRegistryOption("DBMusicDBName");
            txtSQLUserName.Text = RegistryHelper.LoadRegistryOption("DBUsername");
            txtSQLPassword.Text = RegistryHelper.LoadRegistryOption("DBPassword");
            txtCacheFolder.Text = RegistryHelper.LoadRegistryOption("LocalCacheFolder");

            chkCleanVideoDB.Checked = Convert.ToBoolean(RegistryHelper.LoadRegistryOption("CleanVideoDB"));
            chkCleanMusicDB.Checked = Convert.ToBoolean(RegistryHelper.LoadRegistryOption("CleanMusicDB"));
            chkCleanVideoCache.Checked = Convert.ToBoolean(RegistryHelper.LoadRegistryOption("CleanVideoCache"));
            chkCleanMusicCache.Checked = Convert.ToBoolean(RegistryHelper.LoadRegistryOption("CleanMusicCache"));
            chkLogOnly.Checked = Convert.ToBoolean(RegistryHelper.LoadRegistryOption("LogOnly"));
            chkBackup.Checked = Convert.ToBoolean(RegistryHelper.LoadRegistryOption("BackupCacheFiles"));
            txtBackup.Text = RegistryHelper.LoadRegistryOption("BackupFolder");


            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.RowHeadersVisible = false;
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            DataGridViewTextBoxColumn timeColumn = new DataGridViewTextBoxColumn();
            timeColumn.DataPropertyName = "Time";
            timeColumn.HeaderText = "Time";
            timeColumn.FillWeight = 30;
            timeColumn.MinimumWidth = 110;

            DataGridViewTextBoxColumn messageColumn = new DataGridViewTextBoxColumn();
            messageColumn.DataPropertyName = "Message";
            messageColumn.HeaderText = "Message";
            messageColumn.FillWeight = 100;

            dataGridView1.Columns.Add(timeColumn);
            dataGridView1.Columns.Add(messageColumn);

            EventLogHelper.LogName = "XBMC Cache Manager";
            dataGridView1.DataSource = EventLogHelper.ReadEventLogEntries();

            DisplayServiceStatus();
            EnableControls();

            tmrMain.Enabled = true;
        }

        private void cmdOK_Click(object sender, EventArgs e)
        {
            bool isServiceRunning = false;

            // Stop the service
            try
            {
                using (ServiceController sc = new ServiceController("XBMCCacheManager"))
                {
                    if (sc.Status == ServiceControllerStatus.Running)
                    {
                        isServiceRunning = true;
                        sc.Stop();
                    }
                }
            }
            catch { }

            DisplayServiceStatus();

            // Save settings
            RegistryHelper.SaveRegistryOption("DBServer", txtServerName.Text);
            RegistryHelper.SaveRegistryOption("DBVideoDBName", txtVideoDatabase.Text);
            RegistryHelper.SaveRegistryOption("DBMusicDBName", txtMusicDatabase.Text);
            RegistryHelper.SaveRegistryOption("DBUsername", txtSQLUserName.Text);
            RegistryHelper.SaveRegistryOption("DBPassword", txtSQLPassword.Text);
            RegistryHelper.SaveRegistryOption("LocalCacheFolder", txtCacheFolder.Text);

            RegistryHelper.SaveRegistryOption("CleanVideoDB", chkCleanVideoDB.Checked.ToString());
            RegistryHelper.SaveRegistryOption("CleanMusicDB", chkCleanMusicDB.Checked.ToString());
            RegistryHelper.SaveRegistryOption("CleanVideoCache", chkCleanVideoCache.Checked.ToString());
            RegistryHelper.SaveRegistryOption("CleanMusicCache", chkCleanMusicCache.Checked.ToString());
            RegistryHelper.SaveRegistryOption("LogOnly", chkLogOnly.Checked.ToString());
            RegistryHelper.SaveRegistryOption("BackupCacheFiles", chkBackup.Checked.ToString());
            RegistryHelper.SaveRegistryOption("BackupFolder", txtBackup.Text);

            // Restart the service
            if (isServiceRunning)
            {
                try
                {
                    using (ServiceController sc = new ServiceController("XBMCCacheManager"))
                    {
                        sc.Start();
                    }
                }
                catch { }
            }

            DisplayServiceStatus();

            this.Close();
        }

        private void cmdCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            DisplayServiceStatus();
        }

        private void DisplayServiceStatus()
        {
            try
            {
                using (ServiceController sc = new ServiceController("XBMCCacheManager"))
                {
                    if (sc.Status != m_LastStatus)
                    {
                        m_LastStatus = sc.Status;

                        switch (sc.Status)
                        {
                            case ServiceControllerStatus.Running:
                                ctlLED.Value = 1;
                                label1.Text = "The XBMC Cache Manager Service is running.";
                                break;
                            case ServiceControllerStatus.Stopped:
                                ctlLED.Value = 3;
                                label1.Text = "The XBMC Cache Manager Service is stopped.";
                                break;
                            default:
                                ctlLED.Value = 2;
                                label1.Text = String.Format("The XBMC Cache Manager Service is {0}.", sc.Status.ToString());
                                break;
                        }
                    }
                }
            }
            catch
            {
                ctlLED.Value = 3;
                label1.Text = "The XBMC Cache Manager Service does not appear to be installed on this machine.";
            }
        }

        private void cmdCacheFolder_Click(object sender, EventArgs e)
        {
            ctlFolder.SelectedPath = txtCacheFolder.Text;

            if (ctlFolder.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                txtCacheFolder.Text = ctlFolder.SelectedPath;
            }
        }

        private void ctlLED_Click(object sender, EventArgs e)
        {
            try
            {
                using (ServiceController sc = new ServiceController("XBMCCacheManager"))
                {
                    switch (sc.Status)
                    {
                        case ServiceControllerStatus.Running:
                            sc.Stop();
                            break;
                        case ServiceControllerStatus.Stopped:
                            sc.Start();
                            break;
                    }
                }
            }
            catch { }

            DisplayServiceStatus();
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            string message = ((List<EventLogHelperEntry>)dataGridView1.DataSource)[e.RowIndex].Message;
            EventDetails frm = new EventDetails(message);
            frm.ShowDialog(this);
        }

        private void cmdBackup_Click(object sender, EventArgs e)
        {
            ctlFolder.SelectedPath = txtBackup.Text;

            if (ctlFolder.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                txtBackup.Text = ctlFolder.SelectedPath;
            }
        }

        private void chkBackup_CheckedChanged(object sender, EventArgs e)
        {
            EnableControls();
        }

        private void EnableControls()
        {
            lblBackup.Enabled = chkBackup.Checked;
            txtBackup.Enabled = chkBackup.Checked;
            cmdBackup.Enabled = chkBackup.Checked;
        }
    }
}
